package middle;

public class Solution_26 {

    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (B == null) return false;
        boolean flag = dps(A, B);
        return flag || (A != null && (isSubStructure(A.left, B) || isSubStructure(A.right, B)));
    }

    private boolean dps(TreeNode A, TreeNode B) {
        if (B == null) {
            return true;
        } else if (A == null || A.val != B.val) {
            return false;
        }
        return dps(A.left, B.left) && dps(A.right, B.right);
    }

    static class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Solution_26 model = new Solution_26();
        TreeNode A = new TreeNode(4);
        A.left = new TreeNode(2);
        A.left.left = new TreeNode(4);
        A.left.right = new TreeNode(5);
        A.left.left.left = new TreeNode(8);
        A.left.left.right = new TreeNode(9);
        A.right = new TreeNode(3);
        A.right.left = new TreeNode(6);
        A.right.right = new TreeNode(7);
        TreeNode B = new TreeNode(4);
        B.left = new TreeNode(8);
        B.right = new TreeNode(9);

        System.out.println(model.isSubStructure(A, B));
    }
}